'''
Author: your name
Date: 2022-01-31 10:15:38
LastEditTime: 2022-02-05 00:45:37
LastEditors: Please set LastEditors
Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
FilePath: /SimonBackend/SimondeAPI/views.py
'''
import json
import calendar
from django.http import HttpResponse
from .githubCrawler import getUpdate
from .weiboCrawler import getHotNews
from SimondeAPI import models

from django.views.decorators.csrf import csrf_exempt

# Create your views here.
def githubAPI(request):
    data = []
    info_list = getUpdate()
    
    for info in info_list:
        # print(info)
        if "推送" in info["action_human_name"]:
            create_at = info["created_at"]
            create_time_list = str(create_at).split('T')[0].split('-')
            create_time = create_time_list[1] + "-" + create_time_list[2]
            print(create_time)
            nickname = info["author"]["nickname"]
            print(nickname)
            commit_count = info["commit_count"]
            print(commit_count)
            action_human_name = info["action_human_name"]
            # print(action_human_name)
            project_path = info["project"]["name_with_namespace"]
            # print(project_path)
            short_ref_name = info["short_ref_name"]
            # print(short_ref_name)
            event_ref_type = info["event_ref_type"]
            # print(event_ref_type)
            event = action_human_name + " " + project_path + " " + "的 " + short_ref_name + " " + event_ref_type
            print(event)
            p_temp = {
                        "create_time": create_time,
                        "nickname": nickname,
                        "commit_count": commit_count,
                        "event": event
                    }
            data.append(p_temp)
    
    return HttpResponse(json.dumps({"status": 200, "msg": "OK!", "data": data}, ensure_ascii=False))

def storeHotNews():
    news_list = getHotNews()
    news_id_lists = models.ArticalInfo.objects.values_list("news_id")
    news_id_list = list(news_id_lists)
    news_content_lists = models.ArticalInfo.objects.values_list("content")
    news_content_list = list(news_content_lists)
    news_title_lists = models.ArticalInfo.objects.values_list("title")
    news_title_list = list(news_title_lists)
    # print(type(news_id_list))
    for news in news_list:
        news_id = news['idstr']
        # print(news_id)
        news_title = news["source"]
        # print(news_title)
        # news_text = news["text"]
        # print(news_text)
        news_text = news['text_raw']
        # print(news_text)
        created_at = str(news['created_at']).split(' ')
        # print(created_at)
        month = list(calendar.month_abbr).index(created_at[1])
        news_time = str(created_at[5]) + '-' + str(month) + '-' + str(created_at[2]) + ' ' + str(created_at[3])
        # print(news_time)
        news_img = str(news['user']['profile_image_url'])
        # print(news_img)
        artical_info = models.ArticalInfo(news_id=news_id, title=news_title, create_at=news_time, content=news_text, imgURL=news_img, tag1="微博", tag2="tag2")
        if news_id not in news_id_list or news_title not in news_title_list or news_text not in news_content_list:
            artical_info.save()
    

def allArticalAPI(request):
    data = []
    queryset = models.ArticalInfo.objects.all()
    # print(queryset)
    
    storeHotNews()
    
    for i in queryset:
        p_temp = {
            "id": i.id,
            "title": i.title,
            "create_time": str(i.create_at),
            "content": i.content[:42],
            "imgURL": i.imgURL,
            "tag1": i.tag1,
            "tag2": i.tag2
        }
        data.append(p_temp)
    return HttpResponse(json.dumps({"status": 200, "msg": "OK!", "data": data}, ensure_ascii=False))
    

def articalAPI(request):
    data = []
    aid = request.GET.get("aid")
        
    queryset = models.ArticalInfo.objects.filter(id=aid)
    print(queryset)
    
    for i in queryset:
        create_at = i.create_at
        create_time = str(create_at).split("+")[0]
        p_temp = {
            "id": i.id,
            "title": i.title,
            "create_time": create_time,
            "content": i.content,
            "imgURL": i.imgURL,
            "tag1": i.tag1,
            "tag2": i.tag2
        }
        data.append(p_temp)
    return HttpResponse(json.dumps({"status": 200, "msg": "OK!", "data": data}, ensure_ascii=False))
    
@csrf_exempt
def publishMoment(request):
    content = request.POST.get("content")
    print(content)
    imgListStr = request.POST.get("imgList")
    print(imgListStr)

    # imgList = imgListStr.split(',')
    # print(imgList)
    # imgListLen = len(imgList)
    # for i in range(imgList):

    publishInfo = models.MomentInfo(comments=content, imgURL=imgListStr)
    publishInfo.save()
    
    return HttpResponse(json.dumps({"status": 200, "msg": "OK!", "data": "Succeed!"}, ensure_ascii=False))


def momentInfo(request):
    data = []
    queryset = models.MomentInfo.objects.all()

    for i in queryset:
        create_at = i.create_at
        create_time = str(create_at).split("+")[0].split(".")[0]
        p_temp = {
            "id": i.id,
            "comments": i.comments,
            "imgURL": i.imgURL,
            "create_time": create_time,
        }
        data.append(p_temp)
    return HttpResponse(json.dumps({"status": 200, "msg": "OK!", "data": data}, ensure_ascii=False))
